# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from datetime import datetime
import os
import sys
import jinja2

ISODATEFORMAT = '%Y-%m-%d'
ISODATETIMEFORMAT = "%Y-%m-%d %H:%M:%S"
SUPERUSER_ID=1

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_ext', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


class partner_changed_point(osv.osv):
    _name = 'partner.changed.point'
    _columns = {
        'partner_id': fields.many2one('res.partner', u'客户'),
        'changed_point': fields.integer(u'变化积分'),
        'product_id': fields.many2one('product.product', u'积分产品'),
        'point_balance': fields.integer(u'积分余额'),
        'so_id': fields.many2one('sale.order', u'销售订单'),
        'po_id': fields.many2one('purchase.order', u'采购订单'),
        'note': fields.char(u'备注'),
        'carry_over_year': fields.integer(u'结转年份'),
        'carry_over_month': fields.selection([('01', u'一月份'), ('02', u'二月份'), ('03', u'三月份'),
                                              ('04', u'四月份'), ('05', u'五月份'), ('06', u'六月份'),
                                              ('07', u'七月份'), ('08', u'八月份'), ('09', u'九月份'),
                                              ('10', u'十月份'), ('11', u'十一月份'), ('12', u'十二月份')], u'结转月份'),
        'event_id': fields.many2one('point.events', string='积分来源'),
    }


class payment_point_wizard(osv.osv_memory):
    """不是规范的积分活动,而是对于员工 积分的微调(也就是对于员工的积分的 人工的调整)"""
    _name = 'payment.point.wizard'
    _columns = {
        'point_num': fields.integer(u'积分数量', required=True),
        'people_num': fields.integer(u'人数'),
        'note': fields.char(u'发放原因', required=True),
    }
    _defaults = {
        'people_num': lambda s, c, u, ctx=None: len(ctx.get('active_ids')),
        'point_num': 1,
    }

    def onchange_point_num(self, cr, uid, ids, point_num, context=None):
        if point_num:
            if point_num <= 0:
                return {'value': {'point_num': 1},
                        'warning': {'title': u'错误', 'message': u"本次发放的积分只能大于等于1！"}}

    def payment_point_to_partner(self, cr, uid, ids, context=None):
        payment_point_wizard = self.browse(cr, uid, ids, context=context)
        partner_cp_objs = self.pool.get('partner.changed.point')
        hr_employee_ids = context.get('active_ids')
        # events_objs = pool.get('point.events').browse(cr, uid, event_id[0], context=context)
        # if events_objs.provision_point - events_objs.provided_point > 0 and events_objs.is_active:
        for hr_employee_objs in self.pool.get('hr.employee').browse(cr, uid, hr_employee_ids, context=context):

            point_balance = hr_employee_objs.address_home_id.point_balance + payment_point_wizard.point_num
            partner_cp_objs.create(cr, uid, {
                'partner_id': hr_employee_objs.address_home_id.id, 'point_balance': point_balance,
                'changed_point': payment_point_wizard.point_num, 'note': payment_point_wizard.note,}, context=context)
            hr_employee_objs.address_home_id.write({'point_balance': point_balance})
        return True


class point_events(osv.osv):
    """积分申请表 ,也叫积分时间表 ,也就是 积分和活动的一个绑定,从而规范积分的来源 和去处."""
    _name = 'point.events'
    _columns = {
        'name': fields.char(u'活动描述'),
        'provision_point': fields.integer(u'总积分'),
        'check_uid': fields.many2one('res.users', string='审核人'),
        'check_time': fields.datetime(u'审核时间'),
        'provided_point': fields.integer(u'已发放积分'),
        'is_active': fields.boolean(u'是否启用'),
        'group_ids': fields.many2many('res.groups', 'point_events_groups_rel','point_events_id','groups_id', string='面向用户组'),
        'begin_date': fields.date(u'开始时间'),
        'end_date': fields.date(u'结束时间'),
        'unit_point': fields.integer(u'每人单次积分'),
        'state': fields.selection([('draft', u'草稿'), ('confirm', u'已审核')], u'活动状态'),
        'url': fields.char(u'访问的url'),
        'event_code': fields.char(u'活动编码'),
        'point_template_id': fields.many2one('point.template', string='面向用户组'),
    }
    _sql_constraints = [('unique_events_code', 'UNIQUE(event_code)', u'活动编码必须唯一!')]
    _defaults = {
        'is_active': False,
    }

    def confirm_check(self, cr, uid, ids, context=None):
        for point_events_objs in self.browse(cr, uid, ids, context=context):
            point_events_objs.write({'check_uid': uid, 'check_time': datetime.now().strftime(ISODATETIMEFORMAT),
                                     'is_active': True})
        return True

    def create_active_code(self, cr, uid, ids, context=None):
        assert len(ids) == 1, 'This option should only be used for a single id at a time'
        return self.pool['report'].get_action(cr, uid, ids, 'create_point_code', context=context)

    def payment_point(self, cr, uid, event_ids, event_point=0, to_partner_id=0, note_postfix='', context=None):
        if to_partner_id == 0:
            user_objs = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
            to_partner_id = user_objs.partner_id.id
        events_message = ''
        to_partner = self.pool.get('res.partner').browse(cr, SUPERUSER_ID, to_partner_id, context=context)
        for event_row in self.browse(cr, SUPERUSER_ID, event_ids, context=context):
            changed_point = event_row.unit_point
            if changed_point == 0:
                changed_point = event_point
            if changed_point == 0:
                continue

            if not event_row.is_active:
                events_message = u'积分活动未启用!'
            elif (event_row.provision_point - event_row.provided_point >= changed_point
                    and event_row.provision_point > 0)\
                    or (event_row.provision_point == 0): #总积分等于0表示不限制积分
                if (event_row.begin_date and event_row.begin_date and
                                event_row.begin_date < datetime.now().strftime(
                                ISODATETIMEFORMAT) < event_row.begin_date) \
                        or not (event_row.begin_date and event_row.begin_date):
                    datetime.now().strftime(ISODATETIMEFORMAT)
                    to_partner.write({'point_balance': changed_point + to_partner.point_balance})
                    self.pool.get('point.events').write(cr, SUPERUSER_ID, int(event_row.id),
                                                        {
                                                            'provided_point': event_row.provided_point + changed_point},
                                                        context=context)
                    self.pool.get('partner.changed.point').create(cr, SUPERUSER_ID, {'partner_id': to_partner.id,
                                                                            'changed_point': changed_point,
                                                                            'note': event_row.name + note_postfix,
                                                                            'point_balance': to_partner.point_balance,
                                                                            'event_id': event_row.id},
                                                                  context=context)
                    events_message = u'您本次获得%s,现在持有积分%s' % (changed_point, to_partner.point_balance)
                else:
                    events_message = u'活动已经过期!'
            elif event_row.provision_point > 0:
                events_message = u'积分不足，送积分活动暂停！!'
        return events_message


class create_point_code(osv.AbstractModel):
    _name = 'report.create_point_code'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        point_events_objs = self.pool.get('point.events').browse(cr, uid, ids, context=context)[0]
        template = env.get_template("point_qrcode.html")
        return template.render({
            'point_events_id': ids[0],
            'url': point_events_objs.url
        })


class check_in_sign(osv.osv):
    """积分申请表 ,也叫积分时间表 ,也就是 积分和活动的一个绑定,从而规范积分的来源 和去处."""
    _name = 'check.in.sign'
    _columns = {
        'stay_minutes': fields.integer(u'时长(分钟)'),
        'check_in_uid': fields.many2one('res.users', string='签到人'),
        'employee_id': fields.many2one('hr.employee', u'员工'),
        'check_in_time': fields.datetime(u'签入时间'),
        'is_check_out': fields.boolean(u'是否签出'),
        'check_out_time': fields.datetime(u'签出时间'),
        'sign_out_reason':fields.char(u'签出原因'),
        'latitude':fields.float(u'纬度'),
        'longitude':fields.float(u'经度'),
        'sign_out_latitude':fields.float(u'纬度'),
        'sign_out_longitude':fields.float(u'经度'),
        'car_placename':fields.char(u'车辆位置'),
    }


class events_rule(osv.osv):
    _name = 'events.rule'
    _columns = {
        'sequence': fields.integer(u'序列'),
        'is_ok_stop': fields.boolean(u'条件成立立即停止检查'),
        'args': fields.selection([(u'1', u'2')], string='参数'),
        'comparator': fields.selection([(u'=', u'等于'), (u'!=', u'不等于'), (u'>', u'大于'), (u'>=', u'大于等于'),
                                        (u'<', u'小于'), (u'<=', u'小于等于'), (u'not in', u'不在范围内')], string='比较器'),
        'values':fields.char(u'值'),
        'point_template_id': fields.many2one('point.template', string='对应活动模板'),
    }

class point_template(osv.osv):
    _name = 'point.template'
    _columns = {
        'event_code': fields.char(u'活动编码'),
        'template_name': fields.char(u'模板名称'),
        'groups': fields.many2many('res.groups', 'point_template_groups_rel','point_template_id','groups_id', u'面向的用户组'),
        'rule_ids':fields.one2many('events.rule', 'point_template_id', u'条件组'),
        'is_active': fields.boolean(u'是否启用'),
        'point_events_ids':fields.one2many('point.events','point_template_id',u'活动'),
    }
